package com.tong.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Api(value = "分布式锁测试", tags = {"锁测试"})
@RestController
@RequestMapping("/lock")
@Import(RedisLockRegistry.class)
@Slf4j
public class LockController {
    private final RedisLockRegistry redisLockRegistry;

    @Autowired
    public LockController(RedisLockRegistry redisLockRegistry) {
        this.redisLockRegistry = redisLockRegistry;
    }

    @ApiOperation(value = "支付锁")
    @GetMapping("pay")
    public void pay(String orderNo) {
        //创建Redis分布式锁
        Lock lock = redisLockRegistry.obtain("order:" + orderNo);
        try {
            //尝试获取锁
            boolean isLock = lock.tryLock(3, TimeUnit.SECONDS);
            if (isLock) {
                Thread.sleep(10000);
                log.info("obtain lock success");
            } else {
                log.info("obtain lock failed");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //释放分布式锁
            lock.unlock();
        }
    }
}
